import { TOKEN_NAME } from '@/config/global';
import { login} from "@/api/vadmin/login";
import { setToken ,getToken} from "@/utils/auth";
import router from '@/router';

const InitUserInfo = {
  roles: [],
};

// 定义的state初始值
const state = {
  token: localStorage.getItem(TOKEN_NAME) || getToken(), // 默认token不走权限
  userInfo: InitUserInfo,
};

const mutations = {
  setToken(state, token) {
    localStorage.setItem(TOKEN_NAME, token);
    state.token = token;
  },
  removeToken(state) {
    localStorage.removeItem(TOKEN_NAME);
    state.token = '';
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
};

const actions = {
  // async  Login({ commit }, userInfo) {
  //   const username = userInfo.username.trim();
  //   const {password} = userInfo;
  //   const {code} = userInfo;
  //   const {uuid} = userInfo;
  //   const res = await login(username, password, code, uuid)
  //   if (res.code === 200) {
  //     setToken(res.data.token);
  //     this.$router.replace('/vadmin/account').catch(() => '')
  //     commit("setToken", res.data.token);
  //   }else{
  //     throw new Error(res.msg);
  //   }
  // },
  async Login({ commit }, userInfo) {
    const mockLogin = async (userInfo) => {
      const username = userInfo.username.trim();
      const {password} = userInfo;
      const {code} = userInfo;
      const {uuid} = userInfo;
      const res = await login(username, password, code, uuid)
      if (res.code === 200) {
        setToken(res.data.token);
        router.push('/vadmin/account').catch(() => '')
        commit("setToken", res.data.token);
      }else{
        throw new Error(res.msg);
      }

    };
    const res = await mockLogin(userInfo);
    if (res.code === 200) {
      commit('setToken', res.data);
    } else {
      throw res;
    }
  },
  async getUserInfo({ commit, state }) {
    const mockRemoteUserInfo = async (token) => {
      if (token === 'main_token') {
        return {
          name: 'td_main',
          roles: ['ALL_ROUTERS'],
        };
      }
      return {
        name: 'td_dev',
        roles: ['userIndex', 'dashboardBase', 'login'],
      };
    };

    const res = await mockRemoteUserInfo(state.token);

    commit('setUserInfo', res);
  },
  async logout({ commit }) {
    commit('removeToken');
    commit('setUserInfo', InitUserInfo);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
